<script setup lang="ts">
import { ref, watchEffect } from "vue";
import {
  deleteUserUsingPost,
  listUserByPageUsingPost,
} from "@/api/userController";
import API from "@/api";
import message from "@arco-design/web-vue/es/message";
import { dayjs } from "@arco-design/web-vue/es/_utils/date";
import { useLoginUserStore } from "@/store/userStore";

const loginUserStore = useLoginUserStore();

const doDelete = async (record: API.User) => {
  if (!record.id) {
    return;
  }
  const res = await deleteUserUsingPost({
    id: record.id,
  });
  if (res.data.code === 0) {
    await loadDate();
    message.success("删除成功");
  } else {
    message.error("删除失败" + res.data.message);
  }
};

const formSearchParams = ref<API.UserQueryRequest>({});
const handleSearch = () => {
  searchParams.value = {
    ...initSearchParams,
    ...formSearchParams.value,
  };
};
const initSearchParams = {
  current: 1,
  pageSize: 5,
};
const searchParams = ref<API.UserQueryRequest>({
  ...initSearchParams,
});

const dataList = ref<API.User[]>([]);
const total = ref<number>(0);

const loadDate = async () => {
  const res = await listUserByPageUsingPost(searchParams.value);
  if (res.data.code === 0) {
    const records = res.data.data?.records || [];
    const totalCount = res.data.data?.total || 0;

    // 如果当前页没有数据，并且不是第一页，自动回到上一页
    if (records.length === 0 && searchParams.value.current! > 1) {
      searchParams.value = {
        ...searchParams.value,
        current: searchParams.value.current! - 1,
      };
    } else {
      dataList.value = records;
      total.value = totalCount;
    }
  } else {
    message.error("获取用户列表失败" + res.data.message);
  }
};

//监听searchParams 变化，重新加载数据
watchEffect(() => {
  loadDate();
});

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

const columns = [
  {
    title: "ID",
    dataIndex: "id",
  },
  {
    title: "账号",
    dataIndex: "userAccount",
  },
  {
    title: "用户名",
    dataIndex: "userName",
  },
  {
    title: "用户头像",
    dataIndex: "userAvatar",
    slotName: "userAvatar",
  },
  {
    title: "用户简介",
    dataIndex: "userProfile",
  },
  {
    title: "权限",
    dataIndex: "userRole",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    slotName: "createTime",
  },
  {
    title: "更新时间",
    dataIndex: "updateTime",
    slotName: "updateTime",
  },
  {
    title: "操作",
    slotName: "optional",
  },
];
</script>
<template>
  <div id="admin-user-page">
    <a-form
      :model="formSearchParams"
      :style="{ marginBottom: '20px' }"
      label-align="left"
      layout="inline"
      auto-label-width
      @submit="handleSearch"
    >
      <a-form-item field="id" label="用户id">
        <a-input
          allow-clear
          v-model="formSearchParams.id"
          placeholder="请输入用户id"
        />
      </a-form-item>
      <a-form-item field="userName" label="用户名">
        <a-input
          v-model="formSearchParams.userName"
          allow-clear
          placeholder="请输入用户名"
        />
      </a-form-item>
      <a-form-item field="userProfile" label="用户简介">
        <a-input
          allow-clear
          v-model="formSearchParams.userProfile"
          placeholder="请输入用户简介"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100px"
          >搜索
        </a-button>
      </a-form-item>
    </a-form>
    <a-table
      :columns="columns"
      :data="dataList"
      :pagination="{
        current: searchParams.current,
        pageSize: searchParams.pageSize,
        total: total,
        showTotal: true,
        showPageSize: true,
        pageSizeOptions: [5, 10, 20],
      }"
      @page-change="onPageChange"
      @pageSizeChange="(val) => (searchParams.pageSize = val)"
    >
      <template #userAvatar="{ record }">
        <a-image :src="record.userAvatar" width="50" height="50" />
      </template>
      <template #createTime="{ record }">
        {{ dayjs(record.createTime).format("YYYY-MM-DD HH:mm:ss") }}
      </template>
      <template #updateTime="{ record }">
        {{ dayjs(record.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
      </template>
      <template #optional="{ record }">
        <a-space>
          <!-- 判断当前登录用户的ID是否与表格中的ID相同 -->
          <a-button
            v-if="loginUserStore.loginUser.id !== record.id"
            status="danger"
            @click="doDelete(record)"
            >删除
          </a-button>
          <!-- 如果ID相同，则不显示删除按钮 -->
          <a-button v-else disabled status="danger">删除</a-button>
        </a-space>
      </template>
    </a-table>
  </div>
</template>
<style scoped>
#admin-user-page {
  margin-bottom: 50px;
}
</style>
